package com.chucang.shucang.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.chucang.shucang.common.base.redis.RedisUtil;
import com.chucang.shucang.common.base.service.impl.CrudServiceImpl;
import com.chucang.shucang.oms.constant.OmsCacheConstant;
import com.chucang.shucang.oms.dao.BlindBoxOrderItemDao;
import com.chucang.shucang.oms.dto.BlindBoxOrderItemDTO;
import com.chucang.shucang.oms.entity.BlindBoxOrderBaseEntity;
import com.chucang.shucang.oms.entity.BlindBoxOrderItemEntity;
import com.chucang.shucang.oms.executor.MybatisBatchExecutor;
import com.chucang.shucang.oms.service.BlindBoxOrderItemService;
import com.github.yitter.idgen.YitIdHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author flitsneak flitsneak@gmail.com
 * @since 1.0.0 2022-10-12
 */
@Service
@RequiredArgsConstructor
public class BlindBoxOrderItemServiceImpl extends CrudServiceImpl<BlindBoxOrderItemDao, BlindBoxOrderItemEntity, BlindBoxOrderItemDTO> implements BlindBoxOrderItemService {

    private final MybatisBatchExecutor mybatisBatchExecutor;
    private final RedisUtil redisUtil;

    @Override
    public boolean batchSaveItems(BlindBoxOrderBaseEntity orderBaseEntity) {
        List<BlindBoxOrderItemEntity> itemList = new ArrayList<>(64);
        for (int i = 0; i < orderBaseEntity.getOrderNum(); i++) {
            //TODO 原型模式优化
            BlindBoxOrderItemEntity blindBoxOrderItemEntity = new BlindBoxOrderItemEntity();
            BeanUtil.copyProperties(orderBaseEntity, blindBoxOrderItemEntity);
            blindBoxOrderItemEntity.setSerialNum((Integer) redisUtil.popListValue(String.format(OmsCacheConstant.BLIND_BOX_SERIAL_NUMS, orderBaseEntity.getBbId())));
            blindBoxOrderItemEntity.setId(YitIdHelper.nextId());
            itemList.add(blindBoxOrderItemEntity);
        }
        mybatisBatchExecutor.insertOrUpdateBatch(itemList, BlindBoxOrderItemDao.class, (list, dao) -> dao.insertBatch(list));
        return true;
    }
}